package xrz.com.jr;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import myhttps.Http;
import myhttps.HttpConst;
import myhttps.HttpListener;
import myhttps.HttpUtil;
import utils.PopupShow;
import xrz.com.jr.adapter.Adapter_HomeGrid;
import xrz.com.jr.adapter.ImageAdapter;
import xrz.com.jr.entity.Frist;
import xrz.com.jr.entity.Home;
import xrz.com.jr.entity.SearchEntry;
import xrz.com.jr.utils.BaseDialog;
import xrz.com.jr.utils.ExitUtil;
import xrz.com.jr.utils.OpenBrowUtils;
import xrz.com.jr.utils.ScreenUtil;
import xrz.com.jr.view.CircleFlowIndicator;
import xrz.com.jr.view.NoScrollGridView;
import xrz.com.jr.view.ViewFlow;

public class MainActivity extends BaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, AdapterView.OnItemClickListener {
    private EditText edt_search;
    private NoScrollGridView gridview;
    private RadioGroup rg;
    private RadioButton rb1;
    private RadioButton rb2;
    private ViewFlow viewFlow;
    private CircleFlowIndicator indicator;
    private ImageView img_photo;
    private RelativeLayout rtly;
    private Adapter_HomeGrid adapter;
    private int type = 1;
    private List<Frist> list;
    private ImageView Img_Search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ScreenUtil.getInstant().init(this);
        initView();
        rg.setOnCheckedChangeListener(this);
        img_photo.setOnClickListener(this);
        adapter = new Adapter_HomeGrid(this);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(this);
        viewFlow.setViewGroup(TabMainActivity.mViewPager);
        getFrist();
        getData(1);
        ExitUtil.getInstant().addToPool(this);
    }

    private void initView() {
        rtly = (RelativeLayout) findViewById(R.id.rtly);
        edt_search = (EditText) findViewById(R.id.edt_search);
        gridview = (NoScrollGridView) findViewById(R.id.gridview);
        rg = (RadioGroup) findViewById(R.id.radiogroup);
        rb1 = (RadioButton) findViewById(R.id.rb1);
        rb2 = (RadioButton) findViewById(R.id.rb2);
        viewFlow = (ViewFlow) findViewById(R.id.viewflow);
        indicator = (CircleFlowIndicator) findViewById(R.id.viewflowindic);
        img_photo = (ImageView) findViewById(R.id.img_photo);
        Img_Search = (ImageView) findViewById(R.id.img_search);
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                togSoftkeybord(MainActivity.this);
            }
        });
        Img_Search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String key = edt_search.getText().toString();
                if (TextUtils.isEmpty(key)) {
                    Toast.makeText(MainActivity.this, "搜索框不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                Map<String, String> map = HttpUtil.getParams("key", key);
                Http.getInstant().sendRequest(MainActivity.this, true, HttpConst.getSearch, map, new HttpListener() {
                    @Override
                    public void onHttpSuccess(String result) {
                        final List<SearchEntry> datas = JSON.parseArray(result, SearchEntry.class);
                        if(datas.size() == 0){
                            Toast.makeText(MainActivity.this, "未搜索到内容", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        PopupShow.showPop(MainActivity.this, datas, edt_search, new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                OpenBrowUtils.startBrower(MainActivity.this, datas.get(i).getLink().trim());
                                PopupShow.dismiss();
                            }
                        });
                    }

                    @Override
                    public void onHttpError(String error) {

                    }
                });
            }
        });

    }

    /**
     * 隐藏键盘
     *
     * @param ctx
     */
    public void togSoftkeybord(Context ctx) {
        InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edt_search.getWindowToken(), 0); // 强制隐藏键盘
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_photo:
                startActivity(new Intent(MainActivity.this, PersionActivity.class));
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rb1:
                type = 1;
                break;
            case R.id.rb2:
                type = 2;
                break;
        }
        getData(type);
    }

    private void getData(final int type) {
        Map<String, String> map = HttpUtil.getParams("type", type + "");
        Http.getInstant().sendRequest(this, HttpConst.getModel, map, new HttpListener() {
            @Override
            public void onHttpSuccess(String result) {
                List<Home> list = JSON.parseArray(result, Home.class);
                switch(type){
                    case 1:
                        gridview.setNumColumns(4);
                        break;
                    case 2:
                        gridview.setNumColumns(3);
                        break;
                }
                adapter.clear();
                adapter.addAll(list);
            }

            @Override
            public void onHttpError(String error) {

            }
        });
    }

    //获取轮播图
    private void getFrist() {
        Http.getInstant().sendRequest(this, HttpConst.getFrist, new HashMap<String, String>(), new HttpListener() {
            @Override
            public void onHttpSuccess(String result) {
                list = JSON.parseArray(result, Frist.class);
                if (list == null || list.size() == 0) {
                    viewFlow.setVisibility(View.GONE);
                } else {
                    viewFlow.setVisibility(View.VISIBLE);
                    ImageAdapter imageadapter = new ImageAdapter(MainActivity.this, list, rtly);
                    viewFlow.setAdapter(imageadapter);
//                  m_ViewFlow.setViewGroup(scrollview);
                    viewFlow.setTimeSpan(5000);
                    viewFlow.setFlowIndicator(indicator);
                    viewFlow.setSideBuffer(list.size());
                    viewFlow.startAutoFlowTimer();
                }
            }

            @Override
            public void onHttpError(String error) {

            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Home home = adapter.getItem(i);
        if (TextUtils.isEmpty(home.getLink())) {
            if (home.getIsPhone().equals("1")) {
                //电话模块
                Intent intent = new Intent(this, Act_TelModel.class);
                intent.putExtra("id", home.getId());
                intent.putExtra("title", home.getName());
                startActivity(intent);
            } else {
                Intent intent = new Intent(this, Act_NomalModel.class);
                intent.putExtra("id", home.getId());
                intent.putExtra("title", home.getName());
                startActivity(intent);
            }
        } else {
            OpenBrowUtils.startBrower(this, home.getLink().trim());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            BaseDialog.showDialog(MainActivity.this, new BaseDialog.onDialogBtnClickListener() {
                @Override
                public void onClick() {
                    ExitUtil.getInstant().exitApp(MainActivity.this);
                }
            });
        }
        return super.onKeyDown(keyCode, event);
    }

}
